<template>
  <view class="float-button">
    <uni-badge class="uni-badge-left-margin" :text="count" absolute="rightTop" size="small">
      <navigator url="/pages/compose/compose" hover-class="none">
        <uni-icons type="cart" size="30"></uni-icons>
      </navigator>
    </uni-badge>
  </view>
  <view class="left-right">
    <scroll-view scroll-y class="left">
      <view class="title">知识点</view>
      <view
        v-for="item in knowledgeList"
        :key="item.id"
        @tap="onClickKnowledge(item.id)"
        class="item"
        :class="{ active: item.id === state.knowledge_id }"
      >
        <text class="name">{{ item.name }}</text>
      </view>
    </scroll-view>
    <scroll-view class="right" scroll-y enable-flex>
      <!-- <view class="subject">
        <text>学科：</text>
        <radio-group @change="subject_change">
          <label v-for="(item, index) in subject_list" :key="index">
            <radio :value="item.value" :checked="item.checked" style="transform: scale(0.6)" />
            {{ item.name }}
          </label>
        </radio-group>
      </view> -->
      <view class="type_select">
        <text>方式：</text>
        <radio-group @change="type_change">
          <label v-for="(item, index) in type_list" :key="index">
            <radio :value="item.value" :checked="item.checked" style="transform: scale(0.6)" />
            {{ item.name }}
          </label>
        </radio-group>
      </view>
      <view class="subject">
        <text>年级：</text>
        <radio-group @change="grade_change">
          <label v-for="(item, index) in grade_list" :key="index">
            <radio :value="item.value" :checked="item.checked" style="transform: scale(0.6)" />
            {{ item.name }}
          </label>
        </radio-group>
      </view>
      <view class="content">
        <!-- :extra="item.download_total" -->
        <uni-card
          v-for="(item, index) in questionList"
          :key="index"
          :title="item.reference"
          class="guide-content"
          :sub-title="item.publish_time"
          :extra="item.type_cn"
        >
          <mp-html :content="item.content_front"></mp-html>
          <rich-text space="nbsp" :nodes="item.images" class="uni-h6 guide-content"></rich-text>
          <text class="guide-content"></text>
          <text class="bank_point">库币：{{ item.bank_point }}题型：{{ item.type_cn }}</text>
          <button
            @tap="onClickAddToCompose(index)"
            size="mini"
            class="button_content"
            type="primary"
            :disabled="disabledButton(item)"
          >
            组卷
          </button>
        </uni-card>
        <view class="moreButton" v-show="show_more == true">
          <button size="mini" class="button_content" type="primary" @click="onClickMore">
            更多
          </button>
        </view>
      </view>
    </scroll-view>
  </view>
</template>
<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import type {
  SubjectItem,
  KnowledgeItem,
  QuestionItem,
  ComposeTypeItem,
  SelectTypeItem,
} from '@/types/home'
import {
  getKnowledgeAPI,
  getKnowledgeByCourseAPI,
  getQuestionByKnowledgeAPI,
  getQuestionNoAuthAPI,
} from '@/services/home'
import {
  onLoad,
  onPullDownRefresh,
  onShow,
  onReachBottom,
  onShareAppMessage,
} from '@dcloudio/uni-app'
import UniBadge from '@dcloudio/uni-ui/lib/uni-badge/uni-badge.vue'
import UniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'
import { useComposeStore, useDetailStore } from '@/stores'
import mpHtml from '@/components/mp-html/mp-html.vue'
const composeButton = ref(null)
const composeStore = useComposeStore()
const detailStore = useDetailStore()
let composeList = ref<QuestionItem[]>([])
const grade_list = ref<SelectTypeItem[]>([
  { name: '中考', value: '1', checked: true },
  { name: '九下', value: '7', checked: false },
  { name: '九上', value: '6', checked: false },
  { name: '八下', value: '5', checked: false },
  { name: '八上', value: '4', checked: false },
  { name: '七下', value: '3', checked: false },
  { name: '七上', value: '2', checked: false },
])
const fab_config = reactive({
  horizontal: 'left',
  vertical: 'bottom',
  direction: 'horizontal',
  pattern: {
    color: '#7A7E83',
    backgroundColor: '#fff',
    selectedColor: '#ff0000',
    buttonColor: '#007AFF',
    iconColor: '#fff',
  },
  is_color_type: false,
  content: [
    {
      iconPath: '/static/images/blank.png',
      selectedIconPath: '/static/images/5.png',
      text: composeList.value.length.toString(),
      active: true,
    },
  ],
})
const state = reactive({
  grade_id: 0,
  subject_id: 1,
  knowledge_id: 0,
  paper_type: 0,
  page: 1,
  size: 10,
  total: 1,
})
// 选择框列表
const subject_list = ref<SubjectItem[]>([{ name: '数学', value: '1', checked: true }])
let type_list = ref<ComposeTypeItem[]>([
  { name: '按知识点', value: '1', checked: true },
  { name: '按试卷', value: '2', checked: false },
])
// 选中题目个数，利用计算属性
const count = computed(() => {
  return composeList.value.length
})
// 实现更多按钮
const show_more = computed(() => {
  return questionList.value.length < state.total
})
// 判断该试题是否已经在组卷列表中，如果在则不可用，避免加入重复的题目
const disabledButton = (item: any) => {
  let flag = composeList.value.includes(item)
  return flag
}
// 把题目添加到组卷车中
const onClickAddToCompose = (index: number) => {
  if (composeList.value.length < 50) {
    composeList.value.push(questionList.value[index])
    composeStore.setCompose(composeList.value)
  } else {
    uni.showToast({ icon: 'error', title: '最多只能添加50道题目！' })
  }
}
// 知识点点击事件，重新获取该知识点的试题
const onClickKnowledge = (id: number) => {
  console.log('知识点改变：', id)
  state.knowledge_id = id
  state.page = 1
  reGetQuestionData()
  console.log('questionList.value.length', questionList.value.length)
  console.log('state.totle', state.total)
}
// 点击卡片事件，把试题信息保存到缓存中，切换到详情页面
const onClickCard = (item: QuestionItem) => {
  // console.log('浏览题目', item)
  detailStore.setDetail(item)
  uni.navigateTo({ url: '/pages/compose/detail' })
}
// 学科改变了,重新获取该学科的知识点
const subject_change = (e: any) => {
  // console.log('学科改变：', e.target.value)
  state.subject_id = e.target.value
  reGetKnowledgeData()
}
// 组卷方式改变了，切换到该页面或tarbar，根据选择的值判断
const type_change = (e: any) => {
  // console.log('组卷方式改变：', e.target.value)
  if (parseInt(e.target.value) == 2) {
    uni.navigateTo({ url: '/pages/compose/united' })
  }
}
// 年级改变了，重新筛选该年级下的试卷列表
const grade_change = (e: any) => {
  state.grade_id = e.target.value
  console.log('年级改了', state.grade_id)
  getKnowledgeByCourseData()
}
// 获取题目的知识点参数
let knowledgeParams = {
  knowledge_id: state.knowledge_id,
  page: state.page,
  size: state.size,
}
// 根据知识点获取题目（需要登录后）
const questionList = ref<QuestionItem[]>([])
const getQuestionByKnowledgeData = async () => {
  // 获取题目的知识点参数
  knowledgeParams = {
    knowledge_id: state.knowledge_id,
    page: state.page,
    size: state.size,
  }
  const res = await getQuestionByKnowledgeAPI(knowledgeParams)
  console.log('根据知识点获取题目：', res)
  if (Array.isArray(res.results) && res.results.length > 0) {
    questionList.value = res.results
    state.total = res.total
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 无凭证获取题目，用于首次获取题目
const getQuestionNoAuthData = async () => {
  const res = await getQuestionNoAuthAPI()
  console.log('获取默认试题：', res)
  if (Array.isArray(res.results) && res.results.length > 0) {
    questionList.value = res.results
    state.total = res.count
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 获取知识点api的参数
let subjectParams = {
  subject_id: state.subject_id,
}
const knowledgeList = ref<KnowledgeItem[]>([])
console.log('现在去获取知识点')
const getKnowledgeData = async () => {
  // 获取知识点api的参数
  let subjectParams = {
    subject_id: state.subject_id,
  }
  const res = await getKnowledgeAPI(subjectParams)
  console.log('知识点：', res)
  if (Array.isArray(res.results) && res.results.length > 0) {
    knowledgeList.value = res.results
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 获取知识点api的参数
console.log('现在去获取知识点')
const getKnowledgeByCourseData = async () => {
  // 获取知识点api的参数
  let courseParams = {
    course_id: state.grade_id,
  }
  const res = await getKnowledgeByCourseAPI(courseParams)
  console.log('知识点：', res)
  if (Array.isArray(res.results) && res.results.length > 0) {
    knowledgeList.value = res.results
  } else {
    uni.showToast({ icon: 'error', title: '获取失败' })
  }
}
// 重新获取知识点，重新修改参数，再发送api
const reGetKnowledgeData = () => {
  subjectParams = { subject_id: state.subject_id }
  console.log('获取知识点的参数', subjectParams)
  getKnowledgeData()
}
// 重新获取试题列表，重新修改参数，再发送api
const reGetQuestionData = () => {
  knowledgeParams = {
    knowledge_id: state.knowledge_id,
    page: state.page,
    size: state.size,
  }
  // console.log('获取题目的知识点参数', knowledgeParams)
  getQuestionByKnowledgeData()
}
// 页面加载
onLoad(async () => {
  console.log('页面加载')
  getKnowledgeData()
  getQuestionNoAuthData()
})
// 页面显示触发，加载缓存中的已选题目
onShow(() => {
  composeList.value = composeStore.compose
  type_list.value[0].checked = true
  type_list.value[1].checked = false
  // console.log('chapter缓存中的题目：', composeStore.compose)
  // console.log('type_list', type_list.value)
})
onPullDownRefresh(async () => {
  console.log('下拉刷新')
  state.page = 1
  getQuestionByKnowledgeData()
  uni.stopPullDownRefresh()
})
// 用于上拉触底新增试题数据
const addQuestionData = async () => {
  let knowledgeParams = {
    knowledge_id: state.knowledge_id,
    page: state.page + 1,
    size: state.size,
  }
  const res = await getQuestionByKnowledgeAPI(knowledgeParams)
  // console.log('根据知识点获取题目：', res)
  if (Array.isArray(res.results) && res.results.length > 0) {
    questionList.value.push(...res.results)
    state.page += 1
    state.total = res.total
  } else {
    uni.showToast({ icon: 'error', title: '触底添加数据失败' })
  }
}
// 自定义触底加载更多数据
onReachBottom(async () => {
  console.log('触底拉')
  if (questionList.value.length >= state.total) {
    uni.showToast({ title: '没有更多数据了！', icon: 'none' })
  } else {
    addQuestionData()
  }
})
// 点击更多按钮
const onClickMore = () => {
  console.log('更多')
  if (questionList.value.length >= state.total) {
    uni.showToast({ title: '没有更多数据了！', icon: 'none' })
  } else {
    addQuestionData()
  }
}
// 右上角分享
onShareAppMessage(() => {
  return {
    title: '高中技术题库',
    path: '/pages/compose/chapter',
  }
})

// 分享到朋友圈
const onShareTimeline = () => {
  return {
    title: '高中技术',
    path: `/pages/compose/chapter`,
  }
}
</script>

<style lang="scss" scoped>
.fab {
  ::v-deep.uni-icons.uniui-plusempty.fab-circle-icon {
    font-size: 12 !important;
  }

  ::v-deep.uniui-plusempty:before {
    content: '组卷' !important;
    font-size: 12px;
  }
}

.left-right {
  display: flex;
  // flex-flow: row nowrap;
  flex: 1;
  min-height: 400rpx;
}

.left {
  // display: flex;
  // flex-flow: column nowrap;
  // justify-content: left;
  // align-items: flex-start;
  flex: none;
  width: 180rpx;
  overflow: hidden;
  background-color: #f6f6f6;

  .item {
    display: flex;
    // flex-flow: column nowrap;
    justify-content: center;
    align-items: center;
    height: 80rpx;
    font-size: 25rpx;
    color: #596c63;
    position: relative;

    &::after {
      content: '';
      position: absolute;
      left: 42rpx;
      bottom: 0;
      width: 96rpx;
      border-top: 1rpx solid #e3e4e7;
    }
  }

  .active {
    background-color: fff;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      width: 8rpx;
      height: 100%;
      background-color: #0bba88d7;
    }
  }

  .title {
    font-size: 28rpx;
    font-weight: bold;
    overflow: hidden;
  }
}

.left .item:last-child::after,
.left .active::after {
  display: none;
}

.name {
  padding: 3rpx;
  font-size: 22rpx;
  color: #333;
}

.right {
  overflow-y: scroll;
  font-size: 28rpx;
  padding: 1rpx;

  .button_content {
    font-size: 25rpx;
    text-align: left;
  }
}

.subject {
  font-size: 30rpx;
  display: flex;
  flex-flow: row nowrap;
}

.type_select {
  font-size: 30rpx;
  display: flex;
  flex-flow: row nowrap;
}

.content {
  font-size: 27rpx;
  display: flex;
  flex-flow: row wrap;
  height: 100vh;
}

.guide-content {
  font-size: 27rpx;
  display: flex;
  flex-flow: column nowrap;
  justify-content: flex-start;
}

.bank_point {
  font-size: 27rpx;
  color: green;
  display: flex;
  flex-flow: column nowrap;
}

.float-button {
  position: absolute;
  z-index: 999;
  left: 10px;
  top: 10px;
  width: 30px;
  height: 30px;
  background-color: white;
  color: white;
  text-align: center;
  line-height: 30px;
  border-radius: 25px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}

.uni-badge-left-margin {
  margin-left: 0px;
}

.twoButton {
  display: flex;
  flex-flow: row nowrap;
  // align-items: left;
  // justify-items: flex-start;
}

.moreButton {
  display: flex;
  flex-flow: row nowrap;
  align-items: center;
  justify-content: center;
  width: 300rpx;
}
</style>
